package pl.shenlon.poker.game;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;

import net.miginfocom.swing.MigLayout;
import pl.shenlon.poker.game.gametypes.PokerGame;

public class RealPokerPlayer extends PokerPlayer implements ActionListener {

	private final JDialog actionTypeChoiceDialog;

	private JButton buttonFold, buttonRaise, buttonCall, buttonCheck;

	private PlayerActionType selectedActionType;

	public RealPokerPlayer(int cash) {
		super(cash);
		actionTypeChoiceDialog = initDialog();
	}

	@Override
	public PlayerAction act(PokerGame game,
			PlayerActionType... allowedActionTypes) {
		if (isActionAllowed(PlayerActionType.FOLD, allowedActionTypes)) {
			buttonFold.setEnabled(true);
		} else {
			buttonFold.setEnabled(false);
		}

		if (isActionAllowed(PlayerActionType.RAISE, allowedActionTypes)
				&& canBet(game.nextBetAmount())) {
			buttonRaise.setEnabled(true);
		} else {
			buttonRaise.setEnabled(false);
		}

		if (isActionAllowed(PlayerActionType.CALL, allowedActionTypes)
				&& canBet(game.getBetSize())) {
			buttonCall.setEnabled(true);
		} else {
			buttonCall.setEnabled(false);
		}

		if (isActionAllowed(PlayerActionType.CHECK, allowedActionTypes)) {
			buttonCheck.setEnabled(true);
		} else {
			buttonCheck.setEnabled(false);
		}

		actionTypeChoiceDialog.setVisible(true);
		return new PlayerAction(selectedActionType, new GameState(game, this));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		selectedActionType = PlayerActionType.valueOf(e.getActionCommand());
		actionTypeChoiceDialog.setVisible(false);
	}

	private JDialog initDialog() {
		JDialog dialog = new JDialog();
		dialog.setModal(true);
		dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		Container contentPane = dialog.getContentPane();
		contentPane.setLayout(new MigLayout());
		buttonFold = new JButton("Spasuj");
		buttonFold.addActionListener(this);
		buttonFold.setActionCommand("FOLD");
		buttonRaise = new JButton("Podbij");
		buttonRaise.addActionListener(this);
		buttonRaise.setActionCommand("RAISE");
		buttonCall = new JButton("Sprawdź");
		buttonCall.addActionListener(this);
		buttonCall.setActionCommand("CALL");
		buttonCheck = new JButton("Czekaj");
		buttonCheck.addActionListener(this);
		buttonCheck.setActionCommand("CHECK");
		contentPane.add(buttonCall, "w 150");
		contentPane.add(buttonCheck, "w 150, wrap");
		contentPane.add(buttonFold, "w 150");
		contentPane.add(buttonRaise, "w 150, wrap");
		dialog.pack();
		dialog.setLocationRelativeTo(null);
		return dialog;
	}

	private boolean isActionAllowed(PlayerActionType type,
			PlayerActionType... allowedTypes) {
		for (PlayerActionType allowedType : allowedTypes) {
			if (allowedType.equals(type)) {
				return true;
			}
		}
		return false;
	}
}